<template>
  <el-dialog :visible.sync="visible"
             :title="!dataForm.id ? $t('add') : $t('update')"
             :before-close='beforeClose'
             class="tempalte_params_seting"
             :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             v-loading="pageLoading"
             @keyup.enter.native="dataFormSubmitHandle()"
             label-width="120px">
      <el-form-item prop="name"
                    :label="$t('custom.template.fields.set.name')">
        <el-input v-model="dataForm.name"
                  :placeholder="$t('custom.template.fields.set.name')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('custom.template.fields.set.info')">
        <el-table :data="dataForm.info"
                  size='mini'
                  border>
          <el-table-column prop="key"
                           width="200"
                           :label="$t('custom.template.fields.set.infoColKey')">
            <template slot-scope="scope">
              <el-input v-model="scope.row.key"
                        :placeholder="$t('custom.template.fields.set.infoColKey')"
                        size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="fields"
                           width="200"
                           :label="$t('custom.template.fields.set.infoColFields')">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fields"
                        :placeholder="$t('custom.template.fields.set.infoColFields')"
                        size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="type"
                           width="120"
                           :label="$t('custom.template.fields.set.infoColType')">
            <template slot-scope="scope">
              <el-select v-model="scope.row.type"
                         filterable
                         clearable
                         :placeholder="$t('custom.template.fields.set.infoColType')"
                         default-first-option>
           <el-option v-for="item in filedsTypeList"
                           :key="item.id"
                           :label="item.dictLabel"
                           :value="item.dictValue">
                          <span>
                            <i :class="`cuifont ${item.subjectCode}`"></i>
                          </span>
                          <span style="margin-left: 10px">{{ item.dictLabel }}</span>
                           </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="des"
                           :label="$t('custom.template.fields.set.infoColDes')">
            <template slot-scope="scope">
              <el-input v-model="scope.row.des"
                        type="textarea"
                        :placeholder="$t('custom.template.fields.set.infoColDes')"
                        resize
                        :rows="1"
                        size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('custom.template.fields.set.infoColAction')"
                           width="100"
                           align="center">
            <template slot-scope="scope">
              <el-button type="danger"
                         icon="el-icon-delete"
                         circle
                         plain
                         size="mini"
                         :disabled="scope.$index === 0 && dataForm.info.length <= 1"
                         @click="deleteRow(scope.$index,dataForm.info)"></el-button>
              <el-button type="primary"
                         icon="el-icon-plus"
                         circle
                         plain
                         size="mini"
                         @click="addRow(scope.$index,dataForm.info)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item :label="$t('custom.template.fields.set.description')">
        <el-input v-model="dataForm.description"
                  type="textarea"
                  :placeholder="$t('custom.template.fields.set.description')"
                  resize
                  :rows="5"
                  size="mini"></el-input>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button size="small"
                 @click="closeDialog">{{ $t('cancel') }}</el-button>
      <el-button size="small"
                 type="primary"
                 :loading="saveBtnLoading"
                 @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { debounce } from 'lodash'

export default {
  name: 'add-or-edit-template-fields',
  data () {
    return {
      visible: false,
      pageLoading: false,
      saveBtnLoading: false,
      dataForm: {
        id: '',
        name: '',
        info: [{ ...this.infoTemplate }],
        description: null
      },
      infoTemplate: {
        key: null,
        type: null,
        des: null
      }
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    },
    filedsTypeList () {
      return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_fields_description_type_list').dataList
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    getInfo () {
      this.pageLoading = true
      this.$interface.schedule.getTemplateFieldsInfoApi(this.dataForm.id)
        .then(({ data: res }) => {
          this.pageLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataForm = res.data
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    dataFormSubmitHandle: debounce(function () {
      if (!this.validateInfo()) {
        return false
      }
      this.$refs['dataForm'].validate()
        .then(() => {
          this.saveBtnLoading = true
          const changeSysMailTemplate = () => {
            if (!this.dataForm.id) {
              return this.$interface.schedule.postTemplateFieldsApi(this.dataForm)
            } else {
              return this.$interface.schedule.putTemplateFieldsApi(this.dataForm)
            }
          }
          changeSysMailTemplate()
            .then(({ data: res }) => {
              this.saveBtnLoading = false
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$message({
                message: this.$t('prompt.success'),
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.visible = false
                  this.beforeClose()
                  this.$emit('refreshDataList')
                }
              })
            })
            .catch(() => {
              this.saveBtnLoading = false
            })
        })
        .catch(() => { })
    }, 1000, { 'leading': true, 'trailing': false }),
    validateInfo () {
      let tempData = this.dataForm.info
      if (Array.isArray(tempData)) {
        if (tempData.findIndex(e => !e.key) >= 0) {
          this.$message.error(this.$t('custom.tips.required', { fields: 'Info -> Key' }))
          return false
        }
        if (tempData.findIndex(e => !e.type) >= 0) {
          this.$message.error(this.$t('custom.tips.required', { fields: 'Info -> Type' }))
          return false
        }
        if (tempData.findIndex(e => !e.des) >= 0) {
          this.$message.error(this.$t('custom.tips.required', { fields: 'Info -> Description' }))
          return false
        }
        return true
      } else {
        return false
      }
    },
    deleteRow (index, data) {
      if (Array.isArray(data) && data.length >= 1) {
        data.splice(index, 1)
      }
    },
    addRow (index, data) {
      if (Array.isArray(data)) {
        data.splice(index + 1, 0, { ...this.infoTemplate })
      }
    },
    closeDialog () {
      this.visible = false
      this.beforeClose()
    },
    beforeClose (done) {
      Object.assign(this.$data, this.$options.data())
      if (typeof done === 'function') {
        done()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.tempalte_params_seting{
  .el-form-item{
    margin-bottom: 22px !important;
  }
}
</style>
